<template>
  <view class="border-gray h-9 px-2 py-2 box-border flex items-center" @click="openPopup" v-if="parentLength < 3">
    <view class="w-95%">
      <van-tag plain type="primary" v-for="(item, index) in state.cascaderArr" :key="index" class="mr-3">
        <text v-for="(cItem, cIndex) in item" :key="cIndex">{{ cItem.name }}</text>
      </van-tag>
    </view>
    <view class="w-5%">
      <i v-if="state.cascaderArr.length > 0" class="i-ix:clear w-4 h-4" @click.stop="clearData"></i>
    </view>
  </view>
  <van-popup :show="state.show" custom-style="height:50%" round position="bottom" @close="state.show = false">
    <view class="my-3 flex items-center">
      <view class="w-20% text-align-center text-black c-text-14" @click="handleCascaderCancel">取消</view>
      <view class="w-60% text-align-center text-black c-text-16">{{ state.placeholder }}</view>
      <view class="w-20% text-align-center c-color c-text-14" @click="handleCascaderFinish">确定</view>
    </view>
    <van-cascader-multiple multiple :show-header="false" :active-color="'#ffc300'" v-if="state.show" :value="state.cascaderValue" :field-names="{ text: 'name', value: 'id' }" :options="state.cascaderOptions" @change="handleCascaderChange"></van-cascader-multiple>
  </van-popup>
</template>

<script setup lang="ts">
import userRequest from '@/request/userRequest';
import Tools from '@/utils/tools';

interface IState {
  show: boolean;
  placeholder: string;
  cascaderData: IBuildingTreeResNew[];
  cascaderOptions: IBuildingTreeResNew[];
  cascaderValue: string;
  cascaderSelectedOptions: IBuildingTreeResNew[];
  cascaderArr: IBuildingTreeResNew[][];
}

interface IProps {
  floorId?: string;
  unitId?: string;
  buildId?: string;
  villageId?: number;
  selectLevel: number;
  beeperId?: number;
  parentLength: number;
}

type EmitEvents = {
  (
    event: 'onConfirm',
    data: {
      selectedOptions: IBuildingTreeResNew[];
      cascaderArrLength: number;
    },
  ): void;
  (
    event: 'getLocation',
    data: {
      location: string;
    },
  ): void;
};

const props = defineProps<IProps>();
const state = reactive<IState>({
  show: false,
  placeholder: '',
  cascaderOptions: [],
  cascaderData: [],
  cascaderSelectedOptions: [],
  cascaderValue: '',
  cascaderArr: [],
});

const emits = defineEmits<EmitEvents>();

onMounted(() => {
  fetchFloorTreeInformation({
    beeperId: props.beeperId,
  });
  if (props.selectLevel === 1) {
    state.placeholder = '请选择栋';
  } else if (props.selectLevel === 2) {
    state.placeholder = '请选择栋、单元';
  } else if (props.selectLevel === 3) {
    state.placeholder = '请选择栋、单元、层';
  }
});

const openPopup = () => {
  state.show = true;
};

// 地区选择器完成事件
const handleCascaderFinish = () => {
  const { cascaderSelectedOptions } = state;
  const lastItem = state.cascaderSelectedOptions[state.cascaderSelectedOptions.length - 1];
  if (Array.isArray(lastItem)) {
    // 获取每个对象的 id，并拼接成字符串
    const ids = lastItem.map((item) => item.id).join(',');
    state.cascaderValue = ids;
  } else {
    if (lastItem && lastItem.id) {
      state.cascaderValue = String(lastItem.id);
    } else {
      return;
    }
  }
  state.cascaderArr = [];
  if (cascaderSelectedOptions.length >= 3) {
    const firstArray = cascaderSelectedOptions[0];
    const secondArray = cascaderSelectedOptions[1];
    const lastArray = cascaderSelectedOptions[2] as unknown as IBuildingTreeResNew[];
    state.cascaderArr = lastArray.map((item: IBuildingTreeResNew) => [firstArray, secondArray, item]);
  } else if (cascaderSelectedOptions.length === 2) {
    const firstArray = cascaderSelectedOptions[0];
    if (Array.isArray(cascaderSelectedOptions[1])) {
      const secondArray = cascaderSelectedOptions[1] as unknown as IBuildingTreeResNew[];
      state.cascaderArr = secondArray.map((item: IBuildingTreeResNew) => [firstArray, item]);
    } else {
      state.cascaderArr.push([firstArray, cascaderSelectedOptions[1]] as unknown as IBuildingTreeRes[]);
    }
  } else {
    if (Array.isArray(cascaderSelectedOptions[0])) {
      if (cascaderSelectedOptions[0].length === 1) {
        state.cascaderArr.push(cascaderSelectedOptions[0] as unknown as IBuildingTreeRes[]);
      } else {
        state.cascaderArr = cascaderSelectedOptions[0].map((item: IBuildingTreeResNew) => [item]);
      }
    } else {
      state.cascaderArr.push([cascaderSelectedOptions[0]] as unknown as IBuildingTreeRes[]);
    }
  }
  state.show = false;
  emits('onConfirm', {
    selectedOptions: state.cascaderSelectedOptions,
    cascaderArrLength: state.cascaderArr.length,
  });
};

// 地区选择器选中事件
const handleCascaderChange = (e: any) => {
  const { tabIndex, selectedOptions } = e.detail;
  state.cascaderSelectedOptions = selectedOptions;
  const insertData = Tools.findPathDFS<IBuildingTreeResNew>(state.cascaderData, e.detail.value);
  if (!insertData) return;
  const index = state.cascaderData.findIndex((item) => item.id === insertData.id);
  if (tabIndex === 0) {
    state.cascaderOptions = Tools.deEmptyChildrenCascader(state.cascaderData).map((item) => {
      return { ...item, children: [] };
    });
    state.cascaderOptions[index].children = insertData.children;
  }
};

// 获得单元层信息
const fetchFloorTreeInformation = (params: { parentId?: number; beeperId?: number }) => {
  userRequest.BuildingTree(params).then((res) => {
    state.cascaderData = res.data;
    state.cascaderOptions = Tools.deEmptyChildrenCascader(res.data);
    //根据传进来的id获取对应楼栋单元层
    let result: IBuildingTreeResNew[] = [];
    const idToFind = props.floorId || props.unitId || props.buildId;
    if (idToFind) {
      result = findNodeAndAncestors(state.cascaderOptions, idToFind);
      state.cascaderOptions = removeChildrenIfLevelsThreeAndFindNodeById(state.cascaderOptions, idToFind) as unknown as IBuildingTreeResNew[];
    } else {
      removeChildrenIfLevelsThree(state.cascaderOptions);
    }
    emits('getLocation', {
      location: result.map((item) => item.name).join(' / '),
    });
  });
};

// 定义递归函数
const removeChildrenIfLevelsThree = (dataArray: IBuildingTreeResNew[]) => {
  const stack = [...dataArray];
  while (stack.length > 0) {
    const node = stack.pop();
    // 检查当前节点是否为对象，并且存在 levels 属性
    if (typeof node === 'object' && node !== null && 'levels' in node) {
      if (node.levels === props.selectLevel && 'children' in node) {
        try {
          delete node.children;
        } catch (error) {
          console.error('删除失败:', error);
        }
      }
      if (Array.isArray(node.children)) {
        stack.push(...node.children);
      }
    }
  }
};

const findNodeAndAncestors = (data: IBuildingTreeResNew[], id: string) => {
  let resultNode = null;
  let parentNode: any = null;
  let grandparentNode = null;
  const stack = [...data];
  while (stack.length > 0) {
    const node = stack.pop();
    // 检查当前节点是否为目标节点
    if (node?.id === id) {
      resultNode = node; // 找到节点
      break;
    }
    // 如果节点有子节点，推入栈中
    if (node?.children && node.children.length > 0) {
      stack.push(...node.children);
      for (const child of node.children) {
        if (child.id === id) {
          resultNode = child;
          parentNode = node;
          break;
        }
      }
    }
    if (resultNode) {
      break;
    }
  }
  // 查找祖父节点
  if (parentNode) {
    grandparentNode = data.find((item) => item.children && item.children.some((child) => child.id === parentNode.id));
  }
  // 返回结果，调整顺序为祖父节点、父节点、当前节点
  const result = [];
  if (grandparentNode) result.push(grandparentNode); // 祖父节点
  if (parentNode) result.push(parentNode); // 父节点
  if (resultNode) result.push(resultNode); // 当前节点
  return result;
};

const removeChildrenIfLevelsThreeAndFindNodeById = (dataArray: IBuildingTreeResNew[], id: string) => {
  const stack = [...dataArray]; // 使用栈来存储待处理的项
  let foundChildren = null; // 用于存储找到的 children
  while (stack.length > 0) {
    const item = stack.pop(); // 从栈中取出最后一个项
    // 检查当前项的 ID 是否匹配
    if (item && item.id === id) {
      foundChildren = item.children || []; // 如果找到，返回 children，若没有则返回空数组
    }
    // 检查当前项的 levels 属性，移除符合条件的 children
    if (typeof item === 'object' && item !== null && 'levels' in item) {
      if (item.levels === props.selectLevel && 'children' in item) {
        try {
          delete item.children; // 尝试删除 children 属性
        } catch (error) {
          console.error('删除失败:', error);
        }
      }
    }
    // 如果当前项有 children，将其添加到栈中
    if (item && item.children && item.children.length > 0) {
      stack.push(...item.children);
    }
  }
  return foundChildren; // 返回找到的 children
};

const handleCascaderCancel = () => {
  state.show = false;
};

const clearData = () => {
  state.cascaderArr = [];
  state.cascaderSelectedOptions = [];
  state.cascaderValue = '';
  emits('onConfirm', {
    selectedOptions: [],
    cascaderArrLength: 0,
  });
};
</script>

<style scoped>
.border-gray {
  border: 1px solid #ddd;
  border-radius: 16rpx;
}

.border-yellow {
  border-bottom: 3px solid #ffc300;
}

.border-white {
  border-bottom: 3px solid #fff;
}

.tab-class {
  margin-right: 10rpx;
  width: auto;
  height: 60rpx;
  font-size: 28rpx;
  line-height: 60rpx;
}
</style>
